package com.cry.webapp.ui;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Vector;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.BeanNameAware;

import com.opensymphony.xwork2.ActionContext;

public class ContentMenu implements BeanNameAware{
	/**
	 * items came from XML config
	 */
	private HashMap<String, String> items;
	/**
	 * out to the view
	 */
	private Vector<HashMap<String, String>> menuItems;

	/**
	 * Came from meta.menuContent
	 */
	private String requestMenuItems;
	private String namespace;
	private String beanName;
	
	@PostConstruct
	public void init() {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST); 
		requestMenuItems = (String) request.getAttribute("meta." + beanName);
		String servletPath = (String) request.getAttribute("javax.servlet.forward.servlet_path");
	
		/*
		 * Create namespace from request uri 
		 */
		if(servletPath != null) {
			int i=servletPath.length()-1;
			do {
				if(servletPath.charAt(i) == '/') break;
			} while(i-- >= 0);
			
			namespace=servletPath.substring(0,i);
			if(namespace.startsWith("/")) {
				namespace = namespace.substring(1);
			}
		}

		/*
		 * create menuItems as the meta data
		 */
		if(requestMenuItems != null && requestMenuItems.length() > 0) {
			menuItems = new Vector<HashMap<String,String>>();
			for(String allowed : requestMenuItems.split("\\|")) {
				String key = allowed.trim().toLowerCase();
				if(items.containsKey(key)) {
					HashMap<String, String> menuItem = new HashMap<String, String>();
					menuItems.add(menuItem);
					menuItem.put("label", key);
					menuItem.put("url", items.get(key).replaceAll("\\{namespace\\}", namespace));
				}
			}
			
		}
	}
	
	public String execute() {

//		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST); 
//		String menuItemsString = (String) request.getAttribute("meta.menuContent");
//
//		Enumeration<String> attrs =	request.getAttributeNames();
//		
//		while(attrs.hasMoreElements()) {
//			String name=(String) attrs.nextElement();
//			System.out.println(name + ":" + request.getAttribute(name));
//		}
		return "success";
	}

	public Vector<HashMap<String, String>> getMenuItems() {
		return menuItems;
	}

	public void setMenuItems(Vector<HashMap<String, String>> menuItems) {
		this.menuItems = menuItems;
	}

	public HashMap<String, String> getItems() {
		return items;
	}

	public void setItems(HashMap<String, String> items) {
		this.items = items;
	}

	@Override
	public void setBeanName(String name) {
		this.beanName = name;
	}

}
